package tree

/**
  * 思路：main方法里调用初始化方法，将二叉树造出来，遍历是方法一层层调用
  */
object BinaryTreeDemo {
    def main(args: Array[String]): Unit = {

        val tree:BinaryTree[Int] = initTree()
        tree.postForeach(println)
    }


    def initTree() :BinaryTree[Int] ={
        val tree: BinaryTree[Int] = new BinaryTree[Int]
        tree.root = new TreeNode[Int](10)
        tree.root.left = new TreeNode[Int](9)
        tree.root.right =new TreeNode[Int](20)
        tree.root.right.left =new TreeNode[Int](15)
        tree.root.right.right =new TreeNode[Int](35)
        tree
    }
}

class BinaryTree[T]{
    var root :TreeNode[T] = _

    /**
      * 遍历
      */
    def preForeach():Unit = {

    }

    def postForeach(op: T => Unit): Unit = {
        if (root != null) {
            if (root.left != null) root.left.postForeach(op)  //这里再次调用 postForeach(op) 方法  因为是节点调用，所以节点类还得有一个遍历的方法
            if (root.right != null) root.right.postForeach(op)
            op(root.value)
        }
    }



}

class TreeNode[T](var value :T){
    var left :TreeNode[T] = _  // 左节点
    var right :TreeNode[T] = _ // 右节点

     var p :TreeNode[T] = _   //父节点

    def postForeach(op: T => Unit): Unit = {
        if (left != null) left.postForeach(op)
        if (right != null) right.postForeach(op)
        op(value)
    }


}